//
//  MyGoodsOrderTrackingViewModel.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 16/3/15.
//  Copyright © 2016年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "MyGoodsOrderTrackingViewModel.h"
//model
#import "MyGoodsOrderTrackingModel.h"
//unitls
#import "Global.h"
#import "ManagerGlobeUntil.h"
#import "ManagerHttpBase.h"
#import "NSString+Conversion.h"
//vendor
#import "MJExtension.h"
typedef void (^Finished) (BOOL isFinished);
@interface MyGoodsOrderTrackingViewModel ()
@property(nonatomic,weak)Finished isFinished;
@end
@implementation MyGoodsOrderTrackingViewModel
- (id)init {
    self = [super init];
    if (self) {
        _dataSource = [[NSMutableArray alloc]init];
    }
    return self;
}

- (void)parameters:(NSMutableDictionary *)parameters requestSuccess:(void (^)(BOOL isSuccess))success failure:(void(^)(NSString *failureInfo))failureInfo{
    __weak typeof(self) weakSelf = self;
     [self.dataSource removeAllObjects];
     ManagerHttpBase *manager=[ManagerHttpBase sharedManager];
     [manager parameters:parameters customPOST:@"order/track" success:^(AFHTTPRequestOperation *operation, id responseObject) {
         if ([responseObject isKindOfClass:[NSDictionary class]]) {//判读返回数据是否是字典
             NSDictionary *dataDic = (NSDictionary*)responseObject;
             NSString *msg = [dataDic objectForKey:@"MSG"];
             NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
             if ([state isEqualToString:@"0"]) {//请求成功
                 weakSelf.isFinished = success;
                 [weakSelf handleDataSourceWithDatas:[dataDic objectForKey:@"OBJECT"]];
             } else {
                 [weakSelf.dataSource removeAllObjects];
                 failureInfo(msg);
             }
         }
     } failure:^(bool isFailure) {
         failureInfo(@"请求超时");
     }];
}

- (void)handleDataSourceWithDatas:(NSArray*)dataArr{
    if (dataArr.count == 0) {
        self.isFinished(YES);
        return ;
    }
    [self.dataSource addObjectsFromArray:[MyGoodsOrderTrackingModel mj_objectArrayWithKeyValuesArray:dataArr]];
    MyGoodsOrderTrackingModel *firstObject = (MyGoodsOrderTrackingModel*)[self.dataSource firstObject];
    firstObject.isFirst = YES;
    MyGoodsOrderTrackingModel *lastObject = (MyGoodsOrderTrackingModel*)[self.dataSource lastObject];
    lastObject.isLast = YES;
    self.isFinished(YES);
}
@end
